/*
  Applicast API Extension/Utility Library
  XML manipulation utilities

  (c) 2009 ILERRED, S.L.

  Applicast API Extension Library is freely
  distributable under the terms of an MIT-style license.
*/

var XMLUtil = new Object();
Object.extend(XMLUtil, {  
  getNode: function(parent, key) {
    if ( !parent ) return null;
    
    var nodes = parent.getElementsByTagName(key);
    if ( nodes.empty() ) return null;
    
    if ( nodes.length === 1 )
      return nodes[0];
      
    return nodes;
  },
  
  getNodeValue: function(parent, key, greedy) {
    if ( !parent ) return null;
    
    var node = parent.getElementsByTagName(key);
    if ( node.empty() ) return null;
    
    if ( node.length === 1 || !greedy)
      return node[0].nodeValue;
      
    var values = [];
    for (var i=0, m=node.length; i < m; i++)
      values.push(node[i].nodeValue);
    return values;
  },
  
  getChildrenValues: function(parent, childNodeNames) {
    if ( !parent ) return {};
    
    if ( !childNodeNames ) return {};
    
    if ( !Object.isArray(childNodeNames) ) return {};
    
    var results = {};
    for (var i=0, m=childNodeNames.length; i < m; ++i) {
      var k = childNodeNames[i];
      var v = XMLUtil.getNodeValue(parent, k);
      if ( v ) results[k.toLowerCase()] = v;
    }
    
    return results;
  },
  
  responseIsError: function(xml) {
    var error = XMLUtil.getNode(xml, 'Error');
    return !error ? false : true;    
  }
});